import { _decorator, Component, Label, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc'
const { ccclass, property } = _decorator
import { TileManager } from './TileManager'
import { createUINode } from '../../Utils'
import DataManager from '../../Runtime/DataManager'

@ccclass('MapManager')
export class MapManager extends Component {
    async init() {
        const tiles = await this.loadResources()
        const { mapInfo } = DataManager.Instance
        for (let i = 0; i < mapInfo.length; i++) {
            const column = mapInfo[i]
            for (let j = 0; j < column.length; j++) {
                const block = column[j]
                if (block.src == null) {
                    continue
                }
                // draw
                const node = createUINode()
                const spriteFrame = tiles.find(v => v.name === block.src) || tiles[0]

                const tileManager = node.addComponent(TileManager)
                tileManager.init(spriteFrame, i, j, block)
                node.setParent(this.node)
            }
        }
    }
    loadResources() {
        return new Promise<SpriteFrame[]>((resolve, reject) => {
            resources.loadDir('block', SpriteFrame, function (err, assets) {
                if (err) {
                    reject(err)
                    return
                }
                resolve(assets)
            })
        })
    }
}
